package com.taocore.top.title.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.NamingException;

import com.taobao.api.domain.ItemCat;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taocore.top.title.db.DBUtils;
import com.taocore.top.title.db.Dao;

public class CategoriesService {

	static Logger _log = Logger.getLogger(CategoriesService.class.getName());
	
	public static void updateCategories() throws Exception
	{
		Connection conn = null;
		try
		{
			conn = DBUtils.getConnection();
			Dao.INSTANCE.clearCategories(conn);
			ItemcatsGetResponse rsp = TaobaoService.getSubCategories(0L);
			if (rsp.isSuccess())
			{
				List<ItemCat> cat1s = rsp.getItemCats();
				if (cat1s != null)
				{
					Dao.INSTANCE.storeCategories(cat1s, 1, conn);
					for (ItemCat cat1 : cat1s)
					{
						long cat1Id = cat1.getCid();
						ItemcatsGetResponse rsp1 = TaobaoService.getSubCategories(cat1Id);
						if (rsp1.isSuccess())
						{
							List<ItemCat> cat2s = rsp1.getItemCats();
							if (cat2s != null)
							{
								Dao.INSTANCE.storeCategories(cat2s, 2, conn);
								for (ItemCat cat2 : cat2s)
								{
									long cat2Id = cat2.getCid();
									ItemcatsGetResponse rsp2 = TaobaoService.getSubCategories(cat2Id);
									if (rsp2.isSuccess())
									{
										List<ItemCat> cat3s = rsp2.getItemCats();
										if (cat3s != null)
										{
											Dao.INSTANCE.storeCategories(cat3s, 3, conn);
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (NamingException e) {
			_log.log(Level.SEVERE, "", e);
		} catch (SQLException e) {
			_log.log(Level.SEVERE, "", e);
		}
		finally
		{
			DBUtils.close(conn, null, null);
		}
	}
}
